package cn.db.iot.controller;

import cn.db.iot.common.Result;
import cn.db.iot.entity.LoginRequest;
import cn.db.iot.entity.SysUser;
import cn.db.iot.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 认证控制器
 */
@RestController
@RequestMapping("/api/auth")
public class AuthController {
    
    @Autowired
    private SysUserService sysUserService;
    
    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result<Map<String, Object>> login(@RequestBody LoginRequest loginRequest, 
                                           HttpServletRequest request, 
                                           HttpServletResponse response) {
        try {
            String username = loginRequest.getUsername();
            String password = loginRequest.getPassword();
            
            // 验证用户名和密码
            if (username == null || username.trim().isEmpty()) {
                return Result.error("用户名不能为空");
            }
            
            if (password == null || password.trim().isEmpty()) {
                return Result.error("密码不能为空");
            }
            
            // 查询用户
            SysUser user = sysUserService.getByUsername(username);
            if (user == null) {
                return Result.error("用户名或密码错误");
            }
            
            // 验证密码（这里简化处理，实际应该加密验证）
            if (!password.equals(user.getPassword())) {
                return Result.error("用户名或密码错误");
            }
            
            // 检查用户状态
            if (user.getStatus() != null && user.getStatus() == 0) {
                return Result.error("账户已被禁用");
            }
            
            // 创建会话
            HttpSession session = request.getSession();
            session.setAttribute("userId", user.getId());
            session.setAttribute("username", user.getName());
            session.setAttribute("realName", user.getRealName());
            session.setAttribute("userRole", "admin"); // 简化处理
            
            // 设置记住我
            if (loginRequest.getRememberMe() != null && loginRequest.getRememberMe()) {
                session.setMaxInactiveInterval(7 * 24 * 60 * 60); // 7天
            } else {
                session.setMaxInactiveInterval(30 * 60); // 30分钟
            }
            
            // 返回用户信息
            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("id", user.getId());
            userInfo.put("username", user.getName());
            userInfo.put("realName", user.getRealName());
            userInfo.put("email", user.getEmail());
            userInfo.put("mobile", user.getMobile());
            userInfo.put("role", "admin");
            
            return Result.success(userInfo);
            
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("登录失败：" + e.getMessage());
        }
    }
    
    /**
     * 用户登出
     */
    @PostMapping("/logout")
    public Result<String> logout(HttpServletRequest request) {
        try {
            HttpSession session = request.getSession(false);
            if (session != null) {
                session.invalidate();
            }
            return Result.success("登出成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("登出失败：" + e.getMessage());
        }
    }
    
    /**
     * 检查登录状态
     */
    @GetMapping("/check")
    public Result<Map<String, Object>> checkLoginStatus(HttpServletRequest request) {
        try {
            HttpSession session = request.getSession(false);
            Map<String, Object> result = new HashMap<>();
            
            if (session != null && session.getAttribute("userId") != null) {
                result.put("loggedIn", true);
                result.put("userId", session.getAttribute("userId"));
                result.put("username", session.getAttribute("username"));
                result.put("realName", session.getAttribute("realName"));
                result.put("userRole", session.getAttribute("userRole"));
                return Result.success(result);
            } else {
                result.put("loggedIn", false);
                return Result.success(result);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("检查登录状态失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取当前用户信息
     */
    @GetMapping("/userinfo")
    public Result<Map<String, Object>> getUserInfo(HttpServletRequest request) {
        try {
            HttpSession session = request.getSession(false);
            if (session == null || session.getAttribute("userId") == null) {
                return Result.error("用户未登录");
            }
            
            Long userId = (Long) session.getAttribute("userId");
            SysUser user = sysUserService.getById(userId);
            
            if (user == null) {
                return Result.error("用户不存在");
            }
            
            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("id", user.getId());
            userInfo.put("username", user.getName());
            userInfo.put("realName", user.getRealName());
            userInfo.put("email", user.getEmail());
            userInfo.put("mobile", user.getMobile());
            userInfo.put("role", "admin");
            
            return Result.success(userInfo);
            
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取用户信息失败：" + e.getMessage());
        }
    }
}
